# -*- coding: utf-8 -*-
"""
@Project ：weather 
@File    ：weather_data.py
@Author: guzain
@Date:  2025/7/7 11:32:29
@Email： GZA5210@163.com
@Description: 天气数据获取模块
"""
import requests
import time
from utils.log_config import logger
from services.weather_constants import (
    WEATHER_API_BASE_URL, DATE_TOMORROW,
    RAIN_TYPES, get_clean_weather_key
)
from services.weather_info import CITY_ID


def Get_Weather():
    """获取实时天气"""
    clean_weather_key = get_clean_weather_key()
    weather_url = f'{WEATHER_API_BASE_URL}/weather/now?key={clean_weather_key}&location={CITY_ID}'
    try:
        weather_json = requests.get(weather_url).json()
        logger.debug(f"实时天气API响应: {weather_json}")
        weather_code = weather_json.get("code")
        if weather_code == "200":
            weather_now = weather_json.get("now", {})
            weather_text = weather_now.get("text", "未知")  # 获取天气文字
            weather_temp = weather_now.get("temp", "未知")  # 实时获取当前温度
            weather_feels_like = weather_now.get("feelsLike", "未知")  # 获取当前体感温度
            return weather_text, weather_temp, weather_feels_like
        else:
            logger.error(f"访问获取实时天气接口失败，错误码：{weather_code}，响应：{weather_json}")
            return "未知", "未知", "未知"
    except Exception as e:
        logger.error(f"获取实时天气失败：{e}", exc_info=True)
        return "未知", "未知", "未知"


def Get_3d_Weather(num: int):
    """获取三天天气
    Args:
        num: 0表示明天，1表示今天
    Returns:
        天气数据字典
    """
    date = time.strftime("%Y-%m-%d", time.localtime())
    clean_weather_key = get_clean_weather_key()
    weather_url = f'{WEATHER_API_BASE_URL}/weather/3d?key={clean_weather_key}&location={CITY_ID}'
    try:
        weather_json = requests.get(weather_url).json()
        logger.debug(f"三天天气API响应: {weather_json}")
        weather_code = weather_json.get("code")
        if weather_code == "200":
            weather_3d = weather_json.get("daily", [])
            for weather in weather_3d:
                if num == 1 and weather.get("fxDate") == date:
                    return weather
                elif num == 0 and weather.get("fxDate") == DATE_TOMORROW:
                    return weather
            logger.warning("未找到匹配的天气数据")
            return {}
        else:
            logger.error(f"访问获取三天天气接口失败，错误码：{weather_code}，响应：{weather_json}")
            return {}
    except Exception as e:
        logger.error(f"获取三天天气失败：{e}", exc_info=True)
        return {}


def Get_today_Weather():
    """获取今日天气数据"""
    weather_text = Get_Weather()[0]
    weather_temp = Get_Weather()[1]
    weather_feels_like = Get_Weather()[2]
    today_json = Get_3d_Weather(1)
    today_sunrise = today_json.get("sunrise", "未知")
    today_sunset = today_json.get("sunset", "未知")
    today_text = today_json.get("textDay", "未知")
    today_temp_high = today_json.get("tempMax", "未知")
    today_temp_low = today_json.get("tempMin", "未知")
    today_humidity = today_json.get("humidity", "未知")
    today_uv_index = today_json.get("uvIndex", "未知")
    
    # 天气提示信息
    weather_greetings = [
        "亲爱的，今天天气",
        "宝贝，今天天气",
        "亲爱的，今日天气",
        "宝贝，今日天气"
    ]
    import random
    greeting = random.choice(weather_greetings)
    
    if today_text in RAIN_TYPES:
        if today_text == '大雨':
            weather_text_str = f'\n{greeting}{today_text}，记得带好雨伞🌂，出门注意安全哦～\n'
        elif today_text == '中雨':
            weather_text_str = f'\n{greeting}{today_text}，带把伞出门，别淋着啦～\n'
        elif today_text == '雷阵雨':
            weather_text_str = f'\n{greeting}{today_text}，小心雷声⚡，别怕，我在呢～\n'
        elif today_text == '暴雨':
            weather_text_str = f'\n{greeting}{today_text}，尽量减少外出，出门一定要注意安全～\n'
        elif today_text in ['大暴雨', '特大暴雨']:
            weather_text_str = f'\n{greeting}{today_text}，非常危险⚠️，尽量不要出门，待在安全的地方哦～\n'
        else:
            weather_text_str = f'\n{greeting}{today_text}，出门带伞，注意路况～\n'
    else:
        weather_text_str = f'\n{greeting}{today_text}，天气真不错呢～\n'
    
    # 当前温度提示
    current_temp = int(weather_temp)
    if current_temp >= 35:
        today_text_str = f"\n{greeting}非常炎热🥵，记得多喝水，做好防暑措施哦～\n"
    elif current_temp >= 30:
        today_text_str = f"\n{greeting}有点热💦，注意防晒，适当补充水分～\n"
    elif current_temp >= 20:
        today_text_str = f"\n{greeting}舒适宜人😊，适合外出活动～\n"
    elif current_temp >= 10:
        today_text_str = f"\n{greeting}有点凉🍂，记得适当添衣～\n"
    else:
        today_text_str = f"\n{greeting}寒冷❄️，一定要穿暖和哦～\n"
    
    # 紫外线等级提示
    uv_index = int(today_uv_index)
    if uv_index >= 11:
        today_uv_index_str = "\n紫外线极强😱，避免外出，必须外出时做好全面防晒！"
    elif uv_index >= 8:
        today_uv_index_str = "\n紫外线很强😎，尽量避免长时间户外活动，外出请做好防晒～"
    elif uv_index >= 5:
        today_uv_index_str = "\n紫外线中等☀️，外出建议涂抹防晒霜，戴帽子和太阳镜～"
    elif uv_index >= 3:
        today_uv_index_str = "\n紫外线较弱😌，可以适当外出活动，敏感人群建议防晒～"
    else:
        today_uv_index_str = "\n紫外线很弱🤗，可以放心外出活动～"
    
    today_text_data = {
        "weather_text": weather_text,
        "weather_temp": weather_temp,
        "weather_feels_like": weather_feels_like,
        "sunrise": today_sunrise,
        "sunset": today_sunset,
        "text": today_text,
        "temp_high": today_temp_high,
        "temp_low": today_temp_low,
        "humidity": today_humidity,
        "uv_index": today_uv_index,
        "weather_text_str": weather_text_str,
        "today_text_str": today_text_str,
        "uv_index_str": today_uv_index_str
    }
    
    return today_text_data


def Get_tomorrow_Weather():
    """获取明日天气数据"""
    tomorrow_json = Get_3d_Weather(0)
    # 明天的天气数据
    tomorrow_sunrise = tomorrow_json.get("sunrise", "未知")
    tomorrow_sunset = tomorrow_json.get("sunset", "未知")
    tomorrow_text = tomorrow_json.get("textDay", "未知")
    tomorrow_temp_high = tomorrow_json.get("tempMax", "未知")
    tomorrow_temp_low = tomorrow_json.get("tempMin", "未知")
    tomorrow_humidity = tomorrow_json.get("humidity", "未知")
    tomorrow_uv_index = tomorrow_json.get("uvIndex", "未知")
    
    # 天气提示信息
    weather_greetings = [
        "亲爱的，明天天气",
        "宝贝，明天天气",
        "亲爱的，明日天气",
        "宝贝，明日天气"
    ]
    import random
    greeting = random.choice(weather_greetings)
    
    if tomorrow_text in RAIN_TYPES:
        if tomorrow_text == '大雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，记得带好雨伞🌂，出门注意安全～\n'
        elif tomorrow_text == '中雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，带把伞出门，别淋着啦～\n'
        elif tomorrow_text == '雷阵雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，小心雷声⚡，别怕～\n'
        elif tomorrow_text == '暴雨':
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，尽量减少外出，出门一定要注意安全～\n'
        elif tomorrow_text in ['大暴雨', '特大暴雨']:
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，非常危险⚠️，尽量不要出门，待在安全的地方哦～\n'
        else:
            tomorrow_text_str = f'\n{greeting}{tomorrow_text}，出门带伞，注意路况～\n'
    else:
        # 非雨天天气提示
        temp_high = int(tomorrow_temp_high)
        temp_low = int(tomorrow_temp_low)
        if temp_high >= 35:
            tomorrow_text_str = f"\n{greeting}非常炎热🥵，记得做好防暑措施～\n"
        elif temp_high >= 30:
            tomorrow_text_str = f"\n{greeting}有点热💦，注意防晒和补水～\n"
        elif temp_high >= 25:
            tomorrow_text_str = f"\n{greeting}温暖舒适😊，适合外出活动～\n"         
        elif temp_high >= 20:
            tomorrow_text_str = f"\n{greeting}凉爽宜人🍃，记得适当添衣～\n"
        elif temp_high >= 10:
            tomorrow_text_str = f"\n{greeting}有点冷🍂，多穿点衣服哦～\n"
        else:
            tomorrow_text_str = f"\n{greeting}寒冷❄️，一定要穿得厚厚的～\n"
    
    tomorrow_text_data = {
        "date": DATE_TOMORROW,
        "text": tomorrow_text,
        "temp_high": tomorrow_temp_high,
        "temp_low": tomorrow_temp_low,
        "humidity": tomorrow_humidity,
        "uv_index": tomorrow_uv_index,
        "sunrise": tomorrow_sunrise,
        "sunset": tomorrow_sunset,
        "weather_text_str": tomorrow_text_str
    }
    
    return tomorrow_text_data
